package com.problem.leetcode;

import java.util.Arrays;

/**
 * @author didi
 * @DESCRIPTION
 * @create 2019-04-21 13:13
 **/
//5,7,7,8,8,10    8
public class Problem34 {

    public static void main(String[] args) {


        int[] result = new Problem34().searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
        System.out.println(result[0]);
        System.out.println(result[1]);
    }

    public int binarySearchL(int[] arr, int target) {   //找左边界
        int begin = 0, end = arr.length - 1;
        while (begin < end) {
            int mid = begin + (end - begin) / 2;
            if (arr[mid] < target) {
                begin = mid + 1;
            } else {
                end = mid;
            }
        }
        return begin;
    }

    public int binarySearchR(int[] arr, int target) {  //找有边界
        int begin = 0, end = arr.length - 1;
        while (begin < end) {
            int mid = begin + (int) Math.ceil((end - begin) / 2.0);
            if (target < arr[mid]) {
                end = mid - 1;
            } else {
                begin = mid;
            }
        }
        return begin;
    }

    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        if (Arrays.binarySearch(nums, target) < 0) {  //首先判断是否存在
            return res;
        } else {
            res[0] = binarySearchL(nums, target); //找左边界
            res[1] = binarySearchR(nums, target);//找右边界
        }
        return res;
    }

}
